﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
  
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                InvokeExcelPrint(System.Windows.Forms.Application.StartupPath + "\\Info.xls", "Sheet1");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public static void InvokeExcelPrint(string strFilePath, string strSheetName)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass xlApp = new ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbooks xlWorkbooks;
            Microsoft.Office.Interop.Excel.Workbook xlWorkbook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorksheet;
            System.Type tyWorkbooks;
            System.Reflection.MethodInfo[] methods;
            object objFilePath;

            object oMissing = System.Reflection.Missing.Value;

            if (!System.IO.File.Exists(strFilePath))
                throw new System.IO.FileNotFoundException();

            try
            {
                xlApp.Visible = true;
                xlWorkbooks = xlApp.Workbooks;
                tyWorkbooks = xlWorkbooks.GetType();
                methods = tyWorkbooks.GetMethods();
                objFilePath = strFilePath;
                xlWorkbook = (Microsoft.Office.Interop.Excel.Workbook)tyWorkbooks.InvokeMember("Open",
                System.Reflection.BindingFlags.InvokeMethod,
                null,
                xlWorkbooks,
                new object[] { objFilePath, true, true });
                xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets[strSheetName];
                //xlWorksheet.PrintPreview(true);
                xlWorksheet.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
                xlWorkbook.Close(oMissing, oMissing, oMissing);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (xlApp != null)
                {
                    xlApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                    xlApp = null;
                }
                GC.Collect();
            }
        }

    }
}
